package com.quan.system.common.amqp.consumer;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quan.common.bean.MailBean;
import com.quan.common.constant.CommonConstant;
import com.quan.common.tools.mail.SendMailUtils;
import com.quan.system.entity.SystemEmployee;
import com.quan.system.entity.SystemSettings;
import com.quan.system.service.SystemEmployeeService;
import com.quan.system.service.SystemSettingsService;
import com.rabbitmq.client.Channel;

import lombok.extern.slf4j.Slf4j;

/**
 * 消费端-消息队列监听 
 * 员工劳动合同到期邮件提醒
 * 
 * @author yhaoquan
 *
 */
@Slf4j
@Component
public class ConsumerMessageHTDQMailNotify {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private SendMailUtils mailUtils;

	@Autowired
	private SystemEmployeeService employeeService;
	
	@Autowired 
    private SystemSettingsService settingsService;

	// 配置监听器
	@RabbitListener(bindings = @QueueBinding(
			// 队列(队列的名称,是否持久化)
			value = @Queue(value = CommonConstant.QUEUE_TOPIC_HTDQ_NOTIFY, durable = "true"),
			// 交换机(交换机的名称,是否持久化,交换机类型)
			exchange = @Exchange(name = CommonConstant.EXCHANGE_TOPIC_MAIL, durable = "true", type = CommonConstant.RABBITMQ_TYPE_TOPIC),
			// 队列Routiny Key
			key = CommonConstant.QUEUE_TOPIC_HTDQ_NOTIFY))

	@RabbitHandler
	public void process(@Payload Map<String, Object> params, @Headers Map<String, Object> headers, Channel channel) throws Exception {
		logger.info("==>【RabbitMQ 消息消费端】开始发送员工劳动合同到期提醒邮件==>队列的名称:{}, 交换机:{}, 路由Key:{}, 消息类型:{}", CommonConstant.QUEUE_TOPIC_HTDQ_NOTIFY, CommonConstant.EXCHANGE_TOPIC_MAIL, CommonConstant.QUEUE_TOPIC_HTDQ_NOTIFY, CommonConstant.RABBITMQ_TYPE_TOPIC);

		//获取员工劳动合同到期提醒，邮件收件人
		SystemSettings settings = this.settingsService.loadSettings();
		
		if(null != settings) { // 收件人不能为空
			if (null != params && params.size() > 0) {
				// 根据ID获取当前到期员工信息
				SystemEmployee emp = this.employeeService.getById(params.get("empId").toString());
				
				// 当前员工劳动合同的到期日期
				LocalDate start = emp.getTermiDate();
				// 当前员工劳动合同的到期日期+30天后的日期
				LocalDate end = start.plusDays(30);
				
				/**
				 * 即将劳动合同到期的员工列表 
				 * 根据当前即将到期员工的（合同到期日）和（合同到期日+30）来查询出即将到期员工 
				 * 合同到期日 >= and 合同到期日+30
				 */
				QueryWrapper<SystemEmployee> queryWrapper = new QueryWrapper<SystemEmployee>();
				queryWrapper.apply("date_format(termi_date, '%Y-%m-%d') >= {0} and date_format(termi_date, '%Y-%m-%d') <= {1}", start, end);
				List<SystemEmployee> list = this.employeeService.list(queryWrapper);
				
				// 邮件模板参数
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("emp", emp);
				map.put("emps", list);
				
				
				MailBean mailBean = new MailBean();
				mailBean.setTo(settings.getEmpTermiEmail());
				mailBean.setSubject("员工劳动合同到期提醒");
				mailBean.setTemplateLocation("mail/HTDQ_Notify.html");
				mailBean.setTemplateData(map);
				
				this.mailUtils.send(mailBean);
			}
		} else {
			log.warn("员工劳动合同到期提醒，未设置收件人邮箱地址");
		}

		// ACK签收（delivery_tag，是否批量签收）
		channel.basicAck((Long) headers.get(AmqpHeaders.DELIVERY_TAG), false);

	}

}
